var mysql = require("mysql");

var pool = mysql.createPool({
    host: '47.107.243.60',
    user: 'Flechazo',
    password: 'MySQL5.7',
    database: 'socket',
    port: 3306
});


//callback为回调方法
async function queryDataBySQL(sql, callback) {
    return await new Promise((reslove,reject)=>{
        pool.getConnection(function (err, connection) {
          connection.query(sql, function (err, result) {
              if (err) { reject(err) } else {
                if(callback){
                  callback(result)
                }
                reslove(1)
              }
  
          });
          connection.release();
          //console.log("close mysql connection");
        });
    })
};
let connectDAO = require('./connect.js')
function dbTrainInfo(sql,processData) {
  //processData为回调方法
  connectDAO.queryDataBySQL(sql, processData);
}

module.exports = server => {
    const { Server } = require("socket.io");
    const io = new Server(server,{cors:true});
    io.on('connection', (socket) => {
        socket.on('deleteUser',async data=>{
            if(data){
                await queryDataBySQL(`DELETE FROM socketAllMsg WHERE id='${data}';`)
            }
            queryDataBySQL(` select count(1) from socketAllMsg;`,(result)=>{
                //在线人数
                io.emit("chat_userCount", result[0])
            })
        })
        
        socket.on('into_chat',async data=>{
            let intoed = null
            const {id,nickname,avatarUrl} = data
            await queryDataBySQL(`SELECT id from socketAllMsg WHERE id = '${id}';`,(result)=>{
                if(JSON.parse(JSON.stringify(result)).length >0 ) intoed = true
            })
            if(intoed) return 
            await queryDataBySQL(`INSERT INTO socketAllMsg ( id,nickname,avatarUrl ) VALUE ( '${id}','${nickname}','${avatarUrl}');`)
            // 通知谁进入聊天室
            data.time = new Date().toLocaleTimeString()
            queryDataBySQL(` select count(1) from socketAllMsg;`,(result)=>{
                //更新在线人数
                io.emit("chat_userCount", result[0])
            })
            io.emit("add_user", data)
            socket.userid = id
        })
        socket.on('send_message',msgInfo=>{
            queryDataBySQL(`UPDATE socketAllMsg SET msg='${msgInfo.msg}' WHERE id = '${socket.userid}';`)
            // 向所有人广播消息
            msgInfo.time = new Date().toLocaleTimeString()
            io.emit('receiveMessage',msgInfo)
        })

        socket.on('out_chatroom',async ()=>{
            await queryDataBySQL(`DELETE FROM socketAllMsg WHERE id='${socket.userid}';`)
            queryDataBySQL(` select count(1) from socketAllMsg;`,(result)=>{
                //更新在线人数
                io.emit("chat_userCount", result[0])
            })
        })

        // 私聊存储数据库
        socket.on('chatWithHe',async data=>{
            const {chatId,fromid,toid} = data
            await queryDataBySQL(`SELECT * FROM personmsg WHERE chatId = '${chatId}';`,(result)=>{
                if(result.length !== 0){

                }else{
                    queryDataBySQL(`INSERT INTO personmsg (chatId) VALUE ('${chatId}');`)
                }
            })
        })

        // 
        socket.on('sendperMsg',async data=>{
            const {fromid,chatId,toid,personMessage,receiveidInfo} = data
            await queryDataBySQL(`UPDATE personmsg SET msg1='${personMessage}' WHERE chatId = '${chatId}';`)
            dbTrainInfo(`SELECT nickname,avatarUrl from userInfo WHERE id = '${fromid}';`,(res)=>{
                res =  JSON.parse(JSON.stringify(res));
                res[0].chatId = chatId
                io.emit('sengperbackMsg',{sendUser:res[0],fromid:toid,toid:fromid,personMessage,time:new Date().getTime(),receiveidInfo})
            }) 
        })


        // 用户退出、断开连接
        socket.on("disconnect", (data) => {
            // socket.emit('out_chatroom')
        })
        // console.log('a user connected');
    });
}
